package com.dongway.netcondition.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.dongway.core.common.Paginator;
import com.dongway.core.common.ValidationException;
import com.dongway.core.service.BaseService;
import com.dongway.core.utils.JdbcUtils;
import com.dongway.netcondition.criteria.DevCriteria;
import com.dongway.netcondition.model.DevInfo;

@Service
public class DevService extends BaseService {

    public List<DevInfo> search(DevCriteria criteria, Paginator paginator) {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuilder sql = new StringBuilder("select t.* from t_dev_info t ");
        if (StringUtils.isNotBlank(criteria.getRoadName())) {
            sql.append("t_road tr where t.road_id = tr.id and tr.name = :roadName");
            map.put("roadName", criteria.getRoadName());
        }
        if (null != criteria.getTollStationId()) {
            JdbcUtils.appendWhereOrAnd(sql);
            sql.append("t.toll_station_id = :tollStationId");
            map.put("tollStationId", criteria.getTollStationId());
        }
        if (null != criteria.getDevId()) {
            JdbcUtils.appendWhereOrAnd(sql);
            sql.append("t.id = :devId");
            map.put("devId", criteria.getDevId());
        }
        if (StringUtils.isNotBlank(criteria.getDevName())) {
            JdbcUtils.appendWhereOrAnd(sql);
            sql.append("t.name = :devName");
            map.put("devName", criteria.getDevName());
        }
        return getDao().query(DevInfo.class, sql.toString(), map, paginator);
    }
    
    
    public DevInfo searchById(int id) {
        String sql = "select * from t_dev_info where id=?";
        return getDao().queryForObject(DevInfo.class, sql, id);
    }
    
    /**
     * 通过收费站ID查询设备相关信息
     * @param id
     * @return
     */
    public DevInfo searchByStationId(int id) {
        String sql = "select t.* from t_dev_info t, t_toll_station tt where tt.id=t.toll_station_id and tt.id=?";
        return getDao().queryForObject(DevInfo.class, sql, id);
    }


    public void deleteById(Integer id) {
        getDao().deleteById(JdbcUtils.getTableName(DevInfo.class), id);
    }


    /**
     * save or update
     * 
     * @param devInfo
     */
    public void update(DevInfo devInfo) {
        if (null == devInfo.getId()) {
            throw new ValidationException("it's necessary for id.");
        }
        if (getDao().isExisted(DevInfo.class, devInfo.getId())) {
            getDao().updateIgnoreNull(devInfo);
        } else {
            getDao().save(devInfo);        
        }
    }
}
